import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_ys7/flutter_ys7.dart';

import 'package:video_player/video_player.dart';

// 萤石云参数
String appKey = 'd83f034dce1c436db7fe1390826184f7';
String accessToken = 'at.amol69o51fqdk1b09cmp6hnq964ipznw-2h7pri9avj-1lqdncs-m5futk1af';
String deviceSerial = 'L36155057';
String verifyCode = 'VSYMIL';
int cameraNo = 0;

class MyButton1 extends StatelessWidget {
  const MyButton1(
      {required this.contentWidget,
      required this.onTapAction,
      required this.direction,
      Key? key})
      : super(key: key);

  final Widget contentWidget;
  final Function onTapAction;
  final int direction;

  @override
  Widget build(BuildContext context) {
    // GestureDetector手势识别 up 事件有时候会不触发
    // 如果手指不是在 GestureDetector widget 上抬起，那么不会触发up事件
    return Listener(
      onPointerDown: (tapDown) {
        print('MyButton was onTapDown!');
        var requestData = new YS7PtzRequestEntity(
          accessToken: accessToken,
          deviceSerial: deviceSerial,
          channelNo: cameraNo,
          direction: this.direction,
          speed: 1,
        );
        FlutterYs7.ptzStart(requestData).then((res) {
          print("onTapDown $res");
        });
      },
      onPointerUp: (tapUp) {
        if (onTapAction != null) {
          onTapAction('myButton was hello world');
        }
        print('MyButton was onTapUp!');
        var requestData = new YS7PtzRequestEntity(
          accessToken: accessToken,
          deviceSerial: deviceSerial,
          channelNo: cameraNo,
          direction: this.direction,
          speed: 1,
        );
        FlutterYs7.ptzStop(requestData).then((res) {
          print("onTapUp $res");
        });
      },
      child: contentWidget,
    );
  }
}

class MyButton2 extends StatelessWidget {
  const MyButton2(
      {required this.contentWidget,
      required this.onTapAction,
      Key? key,
      required this.onTapDown,
      required this.onTapUp})
      : super(key: key);

  final Widget contentWidget;
  final Function onTapAction;
  final Function onTapDown;
  final Function onTapUp;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        // print('MyButton was tapped!');
        if (onTapAction != null) {
          onTapAction('myButton was hello world');
        }
      },
      onTapDown: (tapDown) {
        if (onTapDown != null) {
          onTapDown(tapDown);
        }
      },
      onTapUp: (tapUp) {
        if (onTapUp != null) {
          onTapUp(tapUp);
        }
      },
      child: contentWidget,
    );
  }
}

class MyView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MyViewState();
  }

  void rowTap(int index) {}

  const MyView();
}

class _MyViewState extends State<MyView> {


  String backTime = 'xx';
  int backTimeTmp = 0;
  late Timer startPlayTime;
  late Timer timeId;
  late VideoPlayerController _controller;
  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(
        'https://open.ys7.com/v3/openlive/L36155057_1_2.m3u8?expire=1713881576&id=572545884575772672&t=88024dd2f7ecf28a794995faf850ae0539933fca4c310e1225ce957c1011af26&ev=100');

    _controller.addListener(() {
      setState(() {});
    });
    _controller.setLooping(true);
    _controller.initialize().then((_) => setState(() {}));
    _controller.play();
  }

  @override
  void dispose() {
    //_controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.fromLTRB(0, 50, 0, 0),
      child: Column(
        children: [
          SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Container(
                  padding: const EdgeInsets.only(top: 20.0),
                ),
                const Text('With assets mp4'),
                Container(
                  padding: const EdgeInsets.all(20),
                  child: AspectRatio(
                    aspectRatio: _controller.value.aspectRatio,
                    child: Stack(
                      alignment: Alignment.bottomCenter,
                      children: <Widget>[
                        VideoPlayer(_controller),
                        _ControlsOverlay(controller: _controller),
                        VideoProgressIndicator(_controller,
                            allowScrubbing: true),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          // Container(
          //   height: 200,
          //   child: Ys7VideoView(),
          // ),

          // Row(
          //   mainAxisAlignment: MainAxisAlignment.spaceAround,
          //   children: [
          //     MyButton2(
          //       onTapAction: (str) {
          //         FlutterYs7.initSdk(appKey);
          //       },
          //       contentWidget: Container(
          //         height: 50.0,
          //         padding: const EdgeInsets.all(8.0),
          //         margin:
          //             const EdgeInsets.symmetric(horizontal: 3.0, vertical: 3),
          //         decoration: BoxDecoration(color: Colors.blue),
          //         child: const Center(
          //           child: Text('INIT SDK'),
          //         ),
          //       ),
          //       onTapDown: () {},
          //       onTapUp: () {},
          //     ),
          //     MyButton2(
          //       onTapDown: () {},
          //       onTapUp: () {},
          //       onTapAction: (str) {
          //         FlutterYs7.setAccessToken(accessToken);
          //         FlutterYs7.initEZPlayer(deviceSerial, verifyCode, cameraNo);
          //       },
          //       contentWidget: Container(
          //         height: 50.0,
          //         padding: const EdgeInsets.all(8.0),
          //         margin:
          //             const EdgeInsets.symmetric(horizontal: 3.0, vertical: 3),
          //         decoration: BoxDecoration(color: Colors.blue),
          //         child: const Center(
          //           child: Text('初始化播放器'),
          //         ),
          //       ),
          //     ),
          //     MyButton2(
          //       onTapDown: () {},
          //       onTapUp: () {},
          //       onTapAction: (str) {
          //         FlutterYs7.startRealPlay();
          //       },
          //       contentWidget: Container(
          //         height: 50.0,
          //         padding: const EdgeInsets.all(8.0),
          //         margin:
          //             const EdgeInsets.symmetric(horizontal: 3.0, vertical: 3),
          //         decoration: BoxDecoration(color: Colors.blue),
          //         child: const Center(
          //           child: Text('开始直播'),
          //         ),
          //       ),
          //     ),
          //     MyButton2(
          //       onTapDown: () {},
          //       onTapUp: () {},
          //       onTapAction: (str) {
          //         FlutterYs7.stopRealPlay();
          //       },
          //       contentWidget: Container(
          //         height: 50.0,
          //         padding: const EdgeInsets.all(8.0),
          //         margin:
          //             const EdgeInsets.symmetric(horizontal: 3.0, vertical: 3),
          //         decoration: BoxDecoration(color: Colors.blue),
          //         child: const Center(
          //           child: Text('停止直播'),
          //         ),
          //       ),
          //     ),
          //   ],
          // ),
          Row(
            children: [
              MyButton1(
                direction: 0,
                contentWidget: Container(
                  height: 50.0,
                  padding: const EdgeInsets.all(8.0),
                  margin:
                      const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
                  decoration: BoxDecoration(color: Colors.blue),
                  child: const Center(
                    child: Text('云台向上'),
                  ),
                ),
                onTapAction: () {},
              ),
              MyButton1(
                onTapAction: () {},
                direction: 1,
                contentWidget: Container(
                  height: 50.0,
                  padding: const EdgeInsets.all(8.0),
                  margin:
                      const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
                  decoration: BoxDecoration(color: Colors.blue),
                  child: const Center(
                    child: Text('云台向下'),
                  ),
                ),
              ),
              MyButton1(
                onTapAction: () {},
                direction: 2,
                contentWidget: Container(
                  height: 50.0,
                  padding: const EdgeInsets.all(8.0),
                  margin:
                      const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
                  decoration: BoxDecoration(color: Colors.blue),
                  child: const Center(
                    child: Text('云台向左'),
                  ),
                ),
              ),
              MyButton1(
                onTapAction: () {},
                direction: 3,
                contentWidget: Container(
                  height: 50.0,
                  padding: const EdgeInsets.all(8.0),
                  margin:
                      const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
                  decoration: BoxDecoration(color: Colors.blue),
                  child: const Center(
                    child: Text('云台向右'),
                  ),
                ),
              ),
            ],
          ),
          //       Row(
          //         children: [
          //           MyButton1(
          // onTapAction: (){},
          //             direction: 8,
          //             contentWidget: Container(
          //               height: 50.0,
          //               padding: const EdgeInsets.all(8.0),
          //               margin:
          //               const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
          //               decoration: BoxDecoration(color: Colors.blue),
          //               child: const Center(
          //                 child: Text('放大'),
          //               ),
          //             ),
          //           ),
          //           MyButton1(
          //           onTapAction: (){},
          //             direction: 9,
          //             contentWidget: Container(
          //               height: 50.0,
          //               padding: const EdgeInsets.all(8.0),
          //               margin:
          //               const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
          //               decoration: BoxDecoration(color: Colors.blue),
          //               child: const Center(
          //                 child: Text('缩小'),
          //               ),
          //             ),
          //           ),
          //           MyButton1(
          //           onTapAction: (){},
          //             direction: 10,
          //             contentWidget: Container(
          //               height: 50.0,
          //               padding: const EdgeInsets.all(8.0),
          //               margin:
          //               const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
          //               decoration: BoxDecoration(color: Colors.blue),
          //               child: const Center(
          //                 child: Text('近焦距'),
          //               ),
          //             ),
          //           ),
          //           MyButton1(
          //           onTapAction: (){},
          //             direction: 11,
          //             contentWidget: Container(
          //               height: 50.0,
          //               padding: const EdgeInsets.all(8.0),
          //               margin:
          //               const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
          //               decoration: BoxDecoration(color: Colors.blue),
          //               child: const Center(
          //                 child: Text('远焦距'),
          //               ),
          //             ),
          //           ),
          //         ],
          //       ),
          //       Row(
          //         children: [
          //           MyButton2(
          //             onTapAction: (str) async {
          //               var request = new Ys7VideoRequestEntity();
          //               request.cameraNo = 1;
          //               request.deviceSerial = deviceSerial;
          //               request.verifyCode = verifyCode;
          //               request.startTime = 1630368000000;
          //               request.endTime = 1630425600000;
          //
          //               FlutterYs7.queryPlayback(request,(data) {
          //                 print("hello world");
          //               });
          //             },
          //             contentWidget: Container(
          //               height: 50.0,
          //               padding: const EdgeInsets.all(8.0),
          //               margin:
          //               const EdgeInsets.symmetric(horizontal: 3, vertical: 3),
          //               decoration: BoxDecoration(color: Colors.blue),
          //               child: const Center(
          //                 child: Text('查询回放'),
          //               ),
          //             ), onTapDown: (){}, onTapUp: (){},
          //           ),
          //           MyButton2(
          // onTapDown: (){}, onTapUp: (){},
          //             onTapAction: (str) async {
          //               print('MyButton was tapped!');
          //
          //               DatePicker.showDateTimePicker(context,
          //                   // 是否展示顶部操作按钮
          //                   showTitleActions: true,
          //                   onChanged: (date) {
          //                     // change事件
          //                     print('change $date');
          //                   },
          //                   onConfirm: (DateTime date) async {
          //                     // 确定事件
          //                     print('confirm $date');
          //                     setState(() {
          //                       backTime = date.toString().substring(0, 19);
          //                     });
          //                   },
          //                   // 当前时间
          //                   currentTime: DateTime.now(),
          //                   // 语言
          //                   locale: LocaleType.zh);
          //             },
          //             contentWidget: Container(
          //               height: 50.0,
          //               padding: const EdgeInsets.all(8.0),
          //               margin:
          //               const EdgeInsets.symmetric(horizontal: 3, vertical: 3),
          //               decoration: BoxDecoration(color: Colors.blue),
          //               child: const Center(
          //                 child: Text('选择回放日期时间'),
          //               ),
          //             ),
          //           ),
          //           Text(backTime)
          //         ],
          //       ),
          //       Row(
          //         children: [
          //           MyButton2(
          // onTapDown: (){}, onTapUp: (){},
          //             onTapAction: (str) async {
          //               DateTime date = DateTime.parse(backTime);
          //               var startTime = date.millisecondsSinceEpoch;
          //               var endTime =
          //                   date.millisecondsSinceEpoch + (1000 * 60 * 30);
          //
          //               var videoRequest = new Ys7VideoRequestEntity();
          //               // videoRequest.startTime = 1630422000000;
          //               // videoRequest.endTime = 1630422010000;
          //               videoRequest.startTime = startTime;
          //               videoRequest.endTime = endTime;
          //               FlutterYs7.startPlayback(videoRequest);
          //               getplayBackTime();
          //             },
          //             contentWidget: Container(
          //               height: 50.0,
          //               padding: const EdgeInsets.all(8.0),
          //               margin:
          //               const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
          //               decoration: BoxDecoration(color: Colors.blue),
          //               child: const Center(
          //                 child: Text('开始回放'),
          //               ),
          //             ),
          //           ),
          //           MyButton2(
          //               onTapDown: (){}, onTapUp: (){},
          //             onTapAction: (str) async {
          //               await FlutterYs7.stopPlayback();
          //               if (startPlayTime != null) {
          //                 startPlayTime.cancel();
          //               }
          //             },
          //             contentWidget: Container(
          //               height: 50.0,
          //               padding: const EdgeInsets.all(8.0),
          //               margin:
          //               const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
          //               decoration: BoxDecoration(color: Colors.blue),
          //               child: const Center(
          //                 child: Text('停止回放'),
          //               ),
          //             ),
          //           ),
          //           MyButton2(
          //
          //             onTapDown: (tapDown)async{
          //               startPlayTime.cancel();
          //               backTimeTmp = DateTime.parse(backTime).millisecondsSinceEpoch;
          //               print('当前时间 = $backTimeTmp');
          //
          //               if (timeId != null) timeId.cancel();
          //               timeId = Timer.periodic(const Duration(milliseconds: 100),
          //                       (timer) {
          //                     backTimeTmp -= 15000;
          //                     setState(() {
          //                       backTime =
          //                           DateTime.fromMillisecondsSinceEpoch(backTimeTmp)
          //                               .toString()
          //                               .substring(0, 19);
          //                     });
          //                   });
          //             },
          //             onTapUp: (tapUp)async{
          //               if (timeId != null) {
          //                 timeId.cancel();
          //               }
          //               print('当前时间 = $backTimeTmp');
          //
          //               await FlutterYs7.stopPlayback();
          //
          //               var request = new Ys7VideoRequestEntity();
          //               request.startTime = backTimeTmp;
          //               request.endTime = request.startTime + (1000 * 60 * 30);
          //               FlutterYs7.startPlayback(request);
          //               getplayBackTime();
          //             },
          //             contentWidget: Container(
          //               height: 50.0,
          //               padding: const EdgeInsets.all(8.0),
          //               margin:
          //               const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
          //               decoration: BoxDecoration(color: Colors.blue),
          //               child: const Center(
          //                 child: Text('快退'),
          //               ),
          //             ), onTapAction: (){},
          //           ),
          //           MyButton2(
          //             onTapDown: (tapDown) {
          //               startPlayTime.cancel();
          //               backTimeTmp = DateTime
          //                   .parse(backTime)
          //                   .millisecondsSinceEpoch;
          //               print('当前时间 = $backTimeTmp');
          //
          //               if (timeId != null) timeId.cancel();
          //               timeId = Timer.periodic(const Duration(milliseconds: 100),
          //                       (timer) {
          //                     backTimeTmp += 15000;
          //                     setState(() {
          //                       backTime =
          //                           DateTime.fromMillisecondsSinceEpoch(backTimeTmp)
          //                               .toString()
          //                               .substring(0, 19);
          //                     });
          //                   });
          //             },
          //             onTapUp: (tapUp) async {
          //               if (timeId != null) {
          //                 timeId.cancel();
          //               }
          //               print('当前时间 = $backTimeTmp');
          //
          //               await FlutterYs7.stopPlayback();
          //
          //               var request = new Ys7VideoRequestEntity();
          //               request.startTime = backTimeTmp;
          //               request.endTime = request.startTime + (1000 * 60 * 30);
          //               FlutterYs7.startPlayback(request);
          //               getplayBackTime();
          //             },
          //             contentWidget: Container(
          //               height: 50.0,
          //               padding: const EdgeInsets.all(8.0),
          //               margin:
          //               const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4),
          //               decoration: BoxDecoration(color: Colors.blue),
          //               child: const Center(
          //                 child: Text('快进'),
          //               ),
          //             ), onTapAction: (){},
          //           ),
          //
          //         ],
          //       ),
        ],
      ),
    );
  }

  void getplayBackTime() {
    if (Platform.isIOS) {
      return;
    }
    if (startPlayTime != null) {
      startPlayTime.cancel();
    }
    startPlayTime = Timer.periodic(const Duration(seconds: 1), (timer) async {
      int playTime = await FlutterYs7.getOSDTime();
      var date = DateTime.fromMillisecondsSinceEpoch(playTime);
      setState(() {
        backTime = date.toString().substring(0, 19);
      });
    });
  }
}

class _ControlsOverlay extends StatelessWidget {
  const _ControlsOverlay({required this.controller});

  static const List<Duration> _exampleCaptionOffsets = <Duration>[
    Duration(seconds: -10),
    Duration(seconds: -3),
    Duration(seconds: -1, milliseconds: -500),
    Duration(milliseconds: -250),
    Duration.zero,
    Duration(milliseconds: 250),
    Duration(seconds: 1, milliseconds: 500),
    Duration(seconds: 3),
    Duration(seconds: 10),
  ];
  static const List<double> _examplePlaybackRates = <double>[
    0.25,
    0.5,
    1.0,
    1.5,
    2.0,
    3.0,
    5.0,
    10.0,
  ];

  final VideoPlayerController controller;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        AnimatedSwitcher(
          duration: const Duration(milliseconds: 50),
          reverseDuration: const Duration(milliseconds: 200),
          child: controller.value.isPlaying
              ? const SizedBox.shrink()
              : Container(
                  color: Colors.black26,
                  child: const Center(
                    child: Icon(
                      Icons.play_arrow,
                      color: Colors.white,
                      size: 100.0,
                      semanticLabel: 'Play',
                    ),
                  ),
                ),
        ),
        GestureDetector(
          onTap: () {
            controller.value.isPlaying ? controller.pause() : controller.play();
          },
        ),
        Align(
          alignment: Alignment.topLeft,
          child: PopupMenuButton<Duration>(
            initialValue: controller.value.captionOffset,
            tooltip: 'Caption Offset',
            onSelected: (Duration delay) {
              controller.setCaptionOffset(delay);
            },
            itemBuilder: (BuildContext context) {
              return <PopupMenuItem<Duration>>[
                for (final Duration offsetDuration in _exampleCaptionOffsets)
                  PopupMenuItem<Duration>(
                    value: offsetDuration,
                    child: Text('${offsetDuration.inMilliseconds}ms'),
                  )
              ];
            },
            child: Padding(
              padding: const EdgeInsets.symmetric(
                // Using less vertical padding as the text is also longer
                // horizontally, so it feels like it would need more spacing
                // horizontally (matching the aspect ratio of the video).
                vertical: 12,
                horizontal: 16,
              ),
              child: Text('${controller.value.captionOffset.inMilliseconds}ms'),
            ),
          ),
        ),
        Align(
          alignment: Alignment.topRight,
          child: PopupMenuButton<double>(
            initialValue: controller.value.playbackSpeed,
            tooltip: 'Playback speed',
            onSelected: (double speed) {
              controller.setPlaybackSpeed(speed);
            },
            itemBuilder: (BuildContext context) {
              return <PopupMenuItem<double>>[
                for (final double speed in _examplePlaybackRates)
                  PopupMenuItem<double>(
                    value: speed,
                    child: Text('${speed}x'),
                  )
              ];
            },
            child: Padding(
              padding: const EdgeInsets.symmetric(
                // Using less vertical padding as the text is also longer
                // horizontally, so it feels like it would need more spacing
                // horizontally (matching the aspect ratio of the video).
                vertical: 12,
                horizontal: 16,
              ),
              child: Text('${controller.value.playbackSpeed}x'),
            ),
          ),
        ),
      ],
    );
  }
}
